package com.et.u1.vm.pay;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.et.core.broadcast.PushDataKt;
import com.et.core.goods.GoodsInfo;
import com.et.u1.R;
import com.et.u1.databinding.FragmentPayBinding;
import com.et.u1.uitl.DataKt;
import com.et.u1.uitl.RepeatBtn;
import com.et.u1.uitl.Result;
import com.et.u1.uitl.ZXingUtils;
import com.et.u1.vm.base.BaseFragment;
import com.et.u1.vm.result.ResultFragment;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class PayFragment extends BaseFragment<FragmentPayBinding, PayViewModel> {
    private int num;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                num--;
                binding.countdown.setText(String.valueOf(num)); //更新时间
                Log.d("time", String.valueOf(num));
                if (num == 0) {
                    Objects.requireNonNull(getActivity()).getSupportFragmentManager().popBackStack();
                }
            } else if (msg.what == 2) {
                binding.countdown.setText("120");
                num = 120;
            }
        }
    };
    private Timer timer;

    private boolean isThisFragment = true;

    public static PayFragment newInstance() {
        return new PayFragment();
    }

    @NotNull
    @Override
    public FragmentPayBinding provideViewBinding(@NotNull LayoutInflater inflater, @org.jetbrains.annotations.Nullable ViewGroup container, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return FragmentPayBinding.inflate(inflater, container, false);
    }

    @NotNull
    @Override
    public PayViewModel provideViewModel() {
        return new ViewModelProvider(this).get(PayViewModel.class);
    }


    @Override
    public void initEvent() {
        // TODO custom
        initView();

    }


    private void payTypeUpdate(String payTypes) {
        if (payTypes.contains("41") || payTypes.contains("42")) {
            binding.payForCode.setVisibility(View.VISIBLE);
        } else {
            binding.payForCode.setVisibility(View.GONE);
        }
        if (payTypes.contains("47")) {
            binding.payForFace.setVisibility(View.VISIBLE);
        } else {
            binding.payForFace.setVisibility(View.GONE);
        }
        if (payTypes.contains("4D")) {
            binding.payForCard.setVisibility(View.VISIBLE);
        } else {
            binding.payForCard.setVisibility(View.GONE);
        }
        if (binding.payForFace.getVisibility() == View.VISIBLE) {
            binding.payForFace.setChecked(true);
        } else if (binding.payForCard.getVisibility() == View.VISIBLE) {
            binding.payForCard.setChecked(true);
        } else if (binding.payForCode.getVisibility() == View.VISIBLE) {
            binding.payForCode.setChecked(true);
        }
    }

    @SuppressLint({"NonConstantResourceId", "DefaultLocale"})
    private void initView() {

        if (PushDataKt.getPayTypeData().getValue() != null) {
            payTypeUpdate(PushDataKt.getPayTypeData().getValue());
        }
        PushDataKt.getPayTypeData().observe(requireActivity(), (Observer<String>) this::payTypeUpdate);

        binding.rg.setOnCheckedChangeListener((group, checkedId) -> {
            mHandler.sendEmptyMessage(2);
            switch (checkedId) {
                case R.id.pay_for_card:
                    binding.cardLinear.setVisibility(View.VISIBLE);
                    binding.codeLinear.setVisibility(View.GONE);
                    binding.faceLinear.setVisibility(View.GONE);
                    break;
                case R.id.pay_for_face:
                    binding.cardLinear.setVisibility(View.GONE);
                    binding.codeLinear.setVisibility(View.GONE);
                    binding.faceLinear.setVisibility(View.VISIBLE);
                    break;
                case R.id.pay_for_code:
                    binding.cardLinear.setVisibility(View.GONE);
                    binding.codeLinear.setVisibility(View.VISIBLE);
                    binding.faceLinear.setVisibility(View.GONE);
                    payForCode();
                    break;

            }
        });

        binding.back.setOnClickListener(v -> Objects.requireNonNull(getActivity()).getSupportFragmentManager().popBackStack());
        binding.faceBtn.setOnClickListener(v -> replaceFragment(ResultFragment.newInstance()));


        new RepeatBtn(binding.faceBtn).showRepeatBtn();
        new RepeatBtn(binding.payForCard).clickAnimation();
        new RepeatBtn(binding.payForCode).clickAnimation();
        new RepeatBtn(binding.payForFace).clickAnimation();


        if (DataKt.getSize().x < DataKt.getSize().y && (DataKt.getSize().y) - (DataKt.getSize().x - 20) / 2 <= 700) {
            binding.adv.setVisibility(View.GONE);
        }
        GoodsInfo goodsInfo = mainModel.getPurchasedGoodsInfo();
        assert goodsInfo != null;
        binding.name.setText(goodsInfo.getName());
        binding.balance.setText(String.format("￥%.2f", (goodsInfo.getChannel().getPrice() * goodsInfo.getDiscount() / 10000f)));
        binding.channel.setText(goodsInfo.getChannel().getLabel());
        binding.image.setImageURI(Uri.parse(goodsInfo.getImage()));
    }

    private void payForCode() {
        new Thread(() -> {
            Result result = viewModel.payForQR_code(Objects.requireNonNull(mainModel.getPurchasedGoodsInfo()));
            if (result.getSuccess()) {
                if (!isThisFragment) return;
                try {
                    String qrcode = new JSONObject(result.getContent()).getString("qrcode");
                    Bitmap bitmap = ZXingUtils.createQRImage(qrcode, binding.codeImage.getWidth(), binding.codeImage.getHeight());
                    binding.codeImage.post(() -> binding.codeImage.setImageBitmap(bitmap));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                if (!isThisFragment) return;
                if (Looper.myLooper() == null) {
                    Looper.prepare();
                }
                Toast.makeText(getContext(), "二维码生成失败，请检查网络连接", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }).start();
    }

    @Override
    public void onResume() {
        super.onResume();
        // TODO
        showActionBar(false);
        num = 120;
        timeClocks();
        isThisFragment = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        isThisFragment = false;
    }

    private void timeClocks() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(1);
            }
        }, 1000, 1000);
    }
}